<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// +----------------------------------------------------------------------
// | validate [ NO ZUO NO DIE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2010-2017 http://www.bocweb.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Hanj
// +----------------------------------------------------------------------
 
//----------------------------------
// validate-三方托管验证类
//----------------------------------


class validate extends MY_Controller {

    function __construct(){
        parent::__construct();
        $this->load->helper('valid_helper');
        $this->load->library('netcredit/loan');
    }

    // 绑定接口返回接口
    public function registerReturn()
    {
        $AccountType = $_POST["AccountType"];
        $AuthFee = $_POST["AuthFee"];
        $AuthState = $_POST["AuthState"];
        $AccountNumber = $_POST["AccountNumber"];
        $Mobile = $_POST["Mobile"];
        $Email = $_POST["Email"];
        $RealName = $_POST["RealName"];
        $IdentificationNo = $_POST["IdentificationNo"];
        $LoanPlatformAccount = $_POST["LoanPlatformAccount"];
        $MoneymoremoreId = $_POST["MoneymoremoreId"];
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];
        $dataStr = $AccountType.$AccountNumber.$Mobile.$Email.$RealName.$IdentificationNo.$LoanPlatformAccount.$MoneymoremoreId.$PlatformMoneymoremore.$AuthFee.$AuthState.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;

        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);
        if ($verifySignature and in_array($ResultCode, array('88','16'))) {
            
        	// [success]成功
            redirect(HTML_URL.'#/success?type=0','refresh');
        }else{
        	
        	// [err]错误提示
            $msg = $this->loan->_obj->qdd->register_recode($ResultCode);
            redirect(HTML_URL.'#/error?type=0&msg='.urlencode($msg),'refresh');
        }
    }

    // 绑定接口的跳转页面
    public function registerNotify()
    {

        $AccountType = $_POST["AccountType"];
        $AuthFee = $_POST["AuthFee"];
        $AuthState = $_POST["AuthState"];
        $AccountNumber = $_POST["AccountNumber"];
        $Mobile = $_POST["Mobile"];
        $Email = $_POST["Email"];
        $RealName = $_POST["RealName"];
        $IdentificationNo = $_POST["IdentificationNo"];
        $LoanPlatformAccount = $_POST["LoanPlatformAccount"];
        $MoneymoremoreId = $_POST["MoneymoremoreId"];
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];
        $ReturnTimes = isset($_POST["ReturnTimes"]) ? $_POST["ReturnTimes"] : 0;

        $dataStr = $AccountType.$AccountNumber.$Mobile.$Email.$RealName.$IdentificationNo.$LoanPlatformAccount.$MoneymoremoreId.$PlatformMoneymoremore.$AuthFee.$AuthState.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;

        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);

        logfile("[qdd][notify]register:".print_r($_POST,1));
        if ($verifySignature and in_array($ResultCode, array('88','16'))) {

        	// [success]成功
        	$data['other_account'] = $MoneymoremoreId;
            $data['realname']      = $RealName;
            $data['chinaid']       = $IdentificationNo;
            $data['modify_at']     = date('Y-m-d H:i:s',time());
            $data['chinaid_check'] = 1;

            $this->load->model('account_model','maccount','default');

            
            $this->maccount->update($data,array('id'=>$Remark1));

            //认证成功 发个红包
            if (!$this->cache->get('Cache:redpackage_auth:'.$Remark1)) {

                //缓存一天 防止重复创建
                $result = $this->_sendRedPackage($Remark1,2);
                $this->cache->save('Cache:redpackage_auth:'.$Remark1,$result,86400);
                
                if (!$result) {
                    $this->cache->delete('Cache:redpackage_auth:'.$Remark1);
                }
            }

            // cache delete
            $key = 'Cache:info:user:'.$Remark1;
            $this->cache->delete($key);
        	echo "SUCCESS";
        }
    }

    // 认证返回
    public function fastpayReturn($value='')
    {   
        $MoneymoremoreId = $_POST["MoneymoremoreId"];
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $Action = $_POST["Action"];
        $CardType = $_POST["CardType"];
        $BankCode = $_POST["BankCode"];
        $CardNo = $_POST["CardNo"];
        $BranchBankName = $_POST["BranchBankName"];
        $Province = $_POST["Province"];
        $City = $_POST["City"];
        $WithholdBeginDate = $_POST["WithholdBeginDate"];
        $WithholdEndDate = $_POST["WithholdEndDate"];
        $SingleWithholdLimit = $_POST["SingleWithholdLimit"];
        $TotalWithholdLimit = $_POST["TotalWithholdLimit"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];
        
        if (!empty($CardNo))
        {
            $CardNo = $this->loan->_obj->rsa->decrypt($CardNo);
            if (empty($CardNo))
            {
                $CardNo = "";
            }
        }

        $dataStr = $MoneymoremoreId.$PlatformMoneymoremore.$Action.$CardType.$BankCode.$CardNo.$BranchBankName.$Province.$City.$WithholdBeginDate.$WithholdEndDate.$SingleWithholdLimit.$TotalWithholdLimit.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;

        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }


        
        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);
        if ($verifySignature and in_array($ResultCode, array('88','89'))) {
            
            redirect(HTML_URL.'#/success?type=4','refresh');
        }else{
            
            // [err]错误提示
            $msg = $this->loan->_obj->qdd->fastpay_recode($ResultCode);
            redirect(HTML_URL.'#/error?type=4&msg='.urlencode($msg),'refresh');
        }
    }

    // 认证处理
    public function fastpayNotify($value='')
    {
        $MoneymoremoreId = $_POST["MoneymoremoreId"];
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $Action = $_POST["Action"];
        $CardType = $_POST["CardType"];
        $BankCode = $_POST["BankCode"];
        $CardNo = $_POST["CardNo"];
        $BranchBankName = $_POST["BranchBankName"];
        $Province = $_POST["Province"];
        $City = $_POST["City"];
        $WithholdBeginDate = $_POST["WithholdBeginDate"];
        $WithholdEndDate = $_POST["WithholdEndDate"];
        $SingleWithholdLimit = $_POST["SingleWithholdLimit"];
        $TotalWithholdLimit = $_POST["TotalWithholdLimit"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];
        
        if (!empty($CardNo))
        {

            $CardNo = $this->loan->_obj->rsa->decrypt($CardNo);
            if (empty($CardNo))
            {
                $CardNo = "";
            }
        }

        $dataStr = $MoneymoremoreId.$PlatformMoneymoremore.$Action.$CardType.$BankCode.$CardNo.$BranchBankName.$Province.$City.$WithholdBeginDate.$WithholdEndDate.$SingleWithholdLimit.$TotalWithholdLimit.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;

        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);
        logfile("[qdd][notify]bindcard:".print_r($_POST,1));
        if ($verifySignature and in_array($ResultCode, array('88','89')) and !$CardNo) {
            $this->load->model('account_model','maccount','default');
            $this->load->model("bankcard_model","mban");

            // [success]成功
            $bank_info = $this->mban->get_one(array('aid'=>$Remark1,'status'=>0));
            if (!empty($bank_info) && $bank_info['is_change']) {
                $re = $this->loan->_obj->userBankList(array('other_account' => $MoneymoremoreId));
                logfile("[qdd][notify]userBankList:".print_r($re,1));

                //返回成功后更新account和bankcard
                $where = array("id"=>$bank_info['id']);
                $u_data = array();

                //如果第三方没有正确返回 以我方为准
                if (isset($re['data'])) {
                    
                    $u_data['bank_card'] = $re['data'];
                }
                $u_data['bank_card'] = $re['data'];
                $u_data['status'] = 1;
                $this->mban->update($u_data,$where);

                $where = array('id'=>$Remark1);
                $u_data = array('bid'=>$bank_info['id']);
                $this->maccount->update($u_data,$where);
            }

            // 删除用户缓存信息
            $this->cache->delete('Cache:info:user:'.$Remark1);
            
            echo "SUCCESS";
        }
    }


    // 支付回调页面
    public function rechargeReturn()
    {

        $RechargeMoneymoremore = $_POST["RechargeMoneymoremore"];
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $LoanNo = $_POST["LoanNo"];
        $OrderNo = $_POST["OrderNo"];
        $Amount = $_POST["Amount"];
        $Fee = $_POST['Fee'];
        $FeePlatform = $_POST['FeePlatform'];
        $RechargeType = $_POST["RechargeType"];
        $FeeType = $_POST['FeeType'];
        $CardNoList = $_POST["CardNoList"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];
        
        if (!empty($CardNoList))
        {
            $CardNoList = $this->loan->_obj->rsa->decrypt($CardNoList);
            if (empty($CardNoList))
            {
                $CardNoList = "";
            }
        }
        
        $dataStr = $RechargeMoneymoremore.$PlatformMoneymoremore.$LoanNo.$OrderNo.$Amount.$Fee.$FeePlatform.$RechargeType.$FeeType.$CardNoList.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;

        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);
        if ($verifySignature and in_array($ResultCode, array('88','92'))) {
            
            // [success]成功
            redirect(HTML_URL.'#/success?type=2','refresh');
        }else{
            
            // [err]错误提示
            $msg = $this->loan->_obj->qdd->recharge_recode($ResultCode);
            redirect(HTML_URL.'#/error?type=2&msg='.urlencode($msg),'refresh');
        }
    }

    // 支付状态通知
    public function rechargeNotify()
    {
        $RechargeMoneymoremore = $_POST["RechargeMoneymoremore"];
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $LoanNo = $_POST["LoanNo"];
        $OrderNo = $_POST["OrderNo"];
        $Amount = $_POST["Amount"];
        $Fee = $_POST['Fee'];
        $FeePlatform = $_POST['FeePlatform'];
        $RechargeType = $_POST["RechargeType"];
        $FeeType = $_POST['FeeType'];
        $CardNoList = $_POST["CardNoList"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];
        
        if (!empty($CardNoList))
        {
            $CardNoList = $this->loan->_obj->rsa->decrypt($CardNoList);
            if (empty($CardNoList))
            {
                $CardNoList = "";
            }
        }
        
        $dataStr = $RechargeMoneymoremore.$PlatformMoneymoremore.$LoanNo.$OrderNo.$Amount.$Fee.$FeePlatform.$RechargeType.$FeeType.$CardNoList.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;

        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        logfile("[qdd][notify][rechage]:".print_r($_POST,1));
        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);

        if ($verifySignature and in_array($ResultCode, array('88'))) {
            
            $key = 'Cache:lock:validate:rechargeNotify:'.$OrderNo;

            if (! $this->cache->get($key)) {
                
                $this->cache->save($key, 'start', 60);
                $this->load->model('pay_model', 'mpay', 'default');
                

                $data['status']     = 1;
                $data['fee']        = $Fee;
                $data['request_no'] = $LoanNo;
                $data['return_msg'] = $this->loan->_obj->qdd->recharge_recode($ResultCode);
                $data['return_at']  = date('Y-m-d H:i:s');

                if ($Remark2) {
                    
                    $data['note']   = '平台充值';

                    // 刷新平台余额
                    $this->cache->delete('Cache:manager:money');
                }
                $this->mpay->update($data,array('orderid' => $OrderNo));
                $this->cache->delete($key);

                // 删除用户缓存信息
                $this->cache->delete('Cache:info:user:'.$Remark1);
                $this->cache->delete('Cache:info:user:'.$Remark1);
                
                // // 发送消息
                // $notify = array(
                //     'n' => 1
                //     ,'title' => '充值成功'
                //     ,'msg' => '您成功充值了'.$Amount.'元。'
                // );

                // notify_msg($notify);
                echo "SUCCESS";
            }
        }
    }

    // 提现回调页面
    public function withdrawReturn()
    {

        $WithdrawMoneymoremore = $_POST["WithdrawMoneymoremore"];
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $LoanNo = $_POST["LoanNo"];
        $OrderNo = $_POST["OrderNo"];
        $Amount = $_POST["Amount"];
        $FeeMax = $_POST["FeeMax"];
        $FeeWithdraws = $_POST["FeeWithdraws"];
        $FeePercent = $_POST["FeePercent"];
        $Fee = $_POST["Fee"];
        $FreeLimit = $_POST["FreeLimit"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];

        $dataStr = $WithdrawMoneymoremore.$PlatformMoneymoremore.$LoanNo.$OrderNo.$Amount.$FeeMax.$FeeWithdraws.$FeePercent.$Fee.$FreeLimit.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;

        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);
        if ($verifySignature and in_array($ResultCode, array('88', '89'))) {
            
            // [success]成功
            redirect(HTML_URL.'#/success?type=3','refresh');
        }else{
            
            // [err]错误提示
            $msg = $this->loan->_obj->qdd->withdraws_recode($ResultCode);
            redirect(HTML_URL.'#/error?type=3&msg='.urlencode($msg),'refresh');
        }
    }

    // 提现状态通知
    public function withdrawNotify()
    {
        $WithdrawMoneymoremore = $_POST["WithdrawMoneymoremore"];
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $LoanNo = $_POST["LoanNo"];
        $OrderNo = $_POST["OrderNo"];
        $Amount = $_POST["Amount"];
        $FeeMax = $_POST["FeeMax"];
        $FeeWithdraws = $_POST["FeeWithdraws"];
        $FeePercent = $_POST["FeePercent"];
        $Fee = $_POST["Fee"];
        $FreeLimit = $_POST["FreeLimit"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];

        $dataStr = $WithdrawMoneymoremore.$PlatformMoneymoremore.$LoanNo.$OrderNo.$Amount.$FeeMax.$FeeWithdraws.$FeePercent.$Fee.$FreeLimit.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;

        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        logfile("[qdd][notify][withdraw]:".print_r($_POST,1));
        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);
        if ($verifySignature and in_array($ResultCode, array('88', '89', '90'))) {
            
            // [success]成功
            $key = 'Cache:lock:validate:withdrawNotify:'.$OrderNo;

            if (! $this->cache->get($key)) {
                
                $this->cache->save($key, 'start', 60);
                $this->load->model('withdraw_model', 'mwd', 'default');
                
                if ($ResultCode == '88') {

                    // 成功
                    $data['status']     = 1;
                    //成功之后要判断是否是第一次提现(is_change=1) 如果是第一次提现则更新提现银行卡并且修改bankcard表中is_change=0 不可修改
                    $this->load->model("bankcard_model","mban",'default');
                    
                    $where = array();
                    $bank_info = $this->mban->get_one(array('aid'=>$Remark1,'status'=>0));
                    if (!empty($bank_info) && $bank_info['is_change']) {

                        $where = array("aid"=>$Remark1);
                        $u_data['is_change'] = 0;
                        $this->mban->update($u_data,$where);
                    }
                    

                } elseif($ResultCode == '90') {
                    
                    // 三方待审核
                    $data['status']     = 3;
                } else {

                    // 资金退回
                    $data['status']     = 2;
                }
                $data['fee']        = $FeeWithdraws;
                $data['request_no'] = $LoanNo;
                $data['return_msg'] = $this->loan->_obj->qdd->withdraws_recode($ResultCode);
                $data['return_at']  = date('Y-m-d H:i:s');

                $this->mwd->update($data,array('orderid' => $OrderNo));
                $this->cache->delete($key);

                // 删除用户缓存信息
                $this->cache->delete('Cache:info:user:'.$Remark1);
                $this->cache->delete('Cache:info:funds:assets:'.$Remark1);
                echo "SUCCESS";
            }
        } else {

            $errlog = $dataStr."\n"."[SignInfo:]:".$SignInfo;
            logfile("[qdd][withdrawNotify][dataStr:]:".$errlog,'validate_err');
        }
    }

    // 投资回传
    public function investReturn()
    {

        $LoanJsonList = $_POST["LoanJsonList"];
        $LoanJsonList = urldecode($LoanJsonList);
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];

        $dataStr = $LoanJsonList.$PlatformMoneymoremore.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;
        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);
        if ($verifySignature and in_array($ResultCode, array('88'))) {
            
            // [success]成功
            redirect(HTML_URL.'#/success?type=1','refresh');
        }else{
            
            // [err]错误提示
            $msg = $this->loan->_obj->qdd->transfer_recode($ResultCode);
            redirect(HTML_URL.'#/error?type=1&msg='.urlencode($msg),'refresh');
        }
    }

    // 投资确认
    public function investNotify()
    {

        $LoanJsonList = $_POST["LoanJsonList"];
        $LoanJsonList = urldecode($LoanJsonList);   
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];
        $ReturnTimes = isset($_POST["ReturnTimes"]) ? $_POST["ReturnTimes"] : 0;

        $dataStr = $LoanJsonList.$PlatformMoneymoremore.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;
        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);

        //这里的红包是通过'_'分割的,要换回','
        $Remark2 = str_replace('_', ',', $Remark2);
        
        logfile("[qdd][notify][invest]:".print_r($_POST,1));
        
        // 投资成功
        if ($verifySignature) {


            $tmp = json_decode($LoanJsonList, 1);
            $tmp = $tmp[0];
                
            if (in_array($ResultCode, array('88'))) {
                

                // [success]成功
                $key  = 'Cache:lock:validate:investNotify:'.$tmp['OrderNo'];
                $ikey = "Cache:project:row".$tmp['BatchNo'];
                if (! $this->cache->get($key)) {

                    $this->cache->save($key, 'start', 60);
                    // 判断是否操作过了
                    $this->load->model('investment_model','mint', 'default');
                    $invest = $this->mint->get_one_where_cache(array('orderid' => $tmp['OrderNo']), false, 86400);

                    if (! $invest) {
                        
                        // 计算利息
                        $this->load->model('project_model', 'mpro');
                        $pro = $this->mpro->get_one_id_cache($tmp['BatchNo'],FALSE,60);
                        $interest_will =  round(($pro['rate'] * $pro['days'] * $tmp['Amount'])/ (year_havedays()*100), 2);
                        $c_data = array('pid'           => $tmp['BatchNo']
                                      , 'aid'           => $Remark1
                                      , 'money'         => $tmp['Amount']
                                      , 'rids'          => $Remark2
                                      , 'red_package'   => $Remark3
                                      , 'orderid'       => $tmp['OrderNo']
                                      , 'request_no'    => $tmp['LoanNo']
                                      , 'interest_will' => $interest_will+(floatval($Remark3))
                                      , 'create_at'     => date('Y-m-d H:i:s'));

                        $this->mint->create($c_data);
                    }
                    
                    $this->cache->delete($key);
                    $this->cache->delete($ikey);
                    $this->cache->delete('Cache:info:user:'.$Remark1);
                    $this->cache->delete('Cache:info:funds:assets:'.$Remark1);
                    $this->cache->delete('Cache:lock:funds:rids:'.$Remark1);
                    $this->cache->delete('Cache:project:row'.$tmp['BatchNo']);
                    echo "SUCCESS";
                }
            }
                
            // 删除lock
            $fkey = 'Cache:freeze:funds:investment:'.$tmp['OrderNo'];
            $pkey = 'Cache:freeze:funds:investment:'.$tmp['BatchNo'];
            $rkey = 'Cache:lock:funds:rids:'.$Remark1;

            if ($this->cache->get($fkey)) {
                
                $p_freeze_money = floatval($this->cache->get($pkey));

                if ($tmp['Amount'] <= $p_freeze_money) {
                    
                    $p_freeze_money -= $tmp['Amount'];
                    $this->cache->save($pkey, $p_freeze_money, 3600);
                }

                $mkey = 'Cache:freeze:funds:investment:max_money'.$Remark1.'_'.$tmp['BatchNo'];//该用户该项目当前的总投资额

                $investment_already = floatval($this->cache->get($mkey));

                if ($ResultCode != '88' && $tmp['Amount'] <= $investment_already) {
                    
                    $investment_already -= $tmp['Amount'];
                    $this->cache->save($mkey, $investment_already, 1000);
                }

                // 删除缓存
                $this->cache->delete($fkey);
                $this->cache->delete($rkey);
            }
        } else {

            $errlog = $dataStr."\n"."[SignInfo:]:".$SignInfo;
            logfile("[qdd][investNotify][dataStr:]:".$errlog,'validate_err');
        }
    }

    // 审核回传
    public function payauditReturn()
    {

        $LoanNoList     = $_POST["LoanNoList"];
        $LoanNoListFail = $_POST["LoanNoListFail"];
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $AuditType = $_POST["AuditType"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message  = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];

        $dataStr = $LoanNoList.$LoanNoListFail.$PlatformMoneymoremore.$AuditType
                 . $RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;
        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);
        if ($verifySignature and in_array($ResultCode, array('88'))) {
            
            // [success]成功
            redirect(HTML_URL.'#/success','refresh');
        }else{
            
            // [err]错误提示
            $msg = $this->loan->_obj->qdd->payaudit_recode($ResultCode);
            redirect(HTML_URL.'#/error?msg='.urlencode($msg),'refresh');
        }
    }

    // 审核确认
    public function payauditNotify()
    {

        $LoanNoList     = $_POST["LoanNoList"];
        $LoanNoListFail = $_POST["LoanNoListFail"];
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $AuditType = $_POST["AuditType"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message  = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];

        $dataStr = $LoanNoList.$LoanNoListFail.$PlatformMoneymoremore.$AuditType
                 . $RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;
        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);

        logfile("[qdd][notify][invest]:".print_r($_POST,1));
        
        // 投资成功
        if ($verifySignature and in_array($ResultCode, array('88'))) {

            $iids = explode(',', $LoanNoList);
            $this->load->model('investment_model', 'minv', 'default');

            if ($iids) {

                $key = 'Cache:lock:project:pay:'.$Remark1;

                $iids_tmp = array();
                if ($iid_arr = $this->cache->get($key)) {
                    
                    foreach ($iid_arr as $v) {
                         
                        if (! in_array($v, $iids)) {
                              
                            $iids_tmp[] = $v;
                        }  
                    }
                }

                if ($iids_tmp) {
                    
                    $this->cache->save($key, $iids_tmp, 1000);
                } else {

                    $this->cache->delete($key);
                }

                // 判断类型
                if ($AuditType == 1) {
                    
                    $this->minv->update(array('status' => 1), array('status' => 2, 'in' => array('request_no', $iids)));
                } else {

                    $this->minv->update(array('status' => 3), array('status' => 2, 'in' => array('request_no', $iids)));
                }
            }
            echo 'SUCCESS';
        } else {

            $errlog = $dataStr."\n"."[SignInfo:]:".$SignInfo;
            logfile("[qdd][payauditNotify][dataStr:]:".$errlog,'validate_err');
        }
    }
    
    // 付息/付款 回传
    public function interestReturn()
    {
        $LoanJsonList = $_POST["LoanJsonList"];
        $LoanJsonList = urldecode($LoanJsonList);
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];

        $dataStr = $LoanJsonList.$PlatformMoneymoremore.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;
        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);
        if ($verifySignature and in_array($ResultCode, array('88'))) {
            
            // [success]成功
            redirect(HTML_URL.'#/success','refresh');
        }else{
            
            // [err]错误提示
            $msg = $this->loan->_obj->qdd->transfer_recode($ResultCode);
            redirect(HTML_URL.'#/error?msg='.urlencode($msg),'refresh');
        }
    }

    // 付息/付款 通知确认
    public function interestNotify()
    {
        $LoanJsonList = $_POST["LoanJsonList"];
        $LoanJsonList = urldecode($LoanJsonList);   
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];
        $ReturnTimes = isset($_POST["ReturnTimes"]) ? $_POST["ReturnTimes"] : 0;

        $dataStr = $LoanJsonList.$PlatformMoneymoremore.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;
        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);

        logfile("[qdd][notify][interestNotify]:".print_r($_POST,1));
        
        // 投资成功
        if ($verifySignature) {

            if (in_array($ResultCode, array('88'))) {
                
                $tmp = json_decode($LoanJsonList, 1);
                $key  = 'Cache:lock:validate:interestNotify:'.$Remark1;

                if (! $this->cache->get($key)) {

                    $this->cache->save($key, 'start', 60);
                    $u_data = array();
                    foreach ($tmp as $t) {
                        
                        $data = array();
                        $data['orderid']       = $t['OrderNo'];
                        $data['request_no']    = $t['LoanNo'];
                        $data['status']        = 1;
                        $data['repay_real_at'] = date('Y-m-d H:i:s');
                        $u_data[]              = $data;
                    }

                    $this->load->model('interest_model', 'mint', 'default');

                    // [success]成功
                    $this->mint->update($u_data, 'orderid', 1);
                    $this->cache->delete($key);
                    echo "SUCCESS";
                }
            }
        } else {

            $errlog = $dataStr."\n"."[SignInfo:]:".$SignInfo;
            logfile("[qdd][interestNotify][dataStr:]:".$errlog,'validate_err');
        }
    }

    // 红包返回
    public function rewardNotify() {

        $LoanJsonList = $_POST["LoanJsonList"];
        $LoanJsonList = urldecode($LoanJsonList);   
        $PlatformMoneymoremore = $_POST["PlatformMoneymoremore"];
        $RandomTimeStamp = $_POST["RandomTimeStamp"];
        $Remark1 = $_POST["Remark1"];
        $Remark2 = $_POST["Remark2"];
        $Remark3 = $_POST["Remark3"];
        $ResultCode = $_POST["ResultCode"];
        $Message = $_POST["Message"];
        $SignInfo = $_POST["SignInfo"];
        $ReturnTimes = isset($_POST["ReturnTimes"]) ? $_POST["ReturnTimes"] : 0;

        $dataStr = $LoanJsonList.$PlatformMoneymoremore.$RandomTimeStamp.$Remark1.$Remark2.$Remark3.$ResultCode;
        if($this->loan->_obj->common->getAntiState() == 1)
        {
            $dataStr = strtoupper(md5($dataStr));
        }

        $verifySignature = $this->loan->_obj->rsa->verify($dataStr,$SignInfo);

        logfile("[qdd][notify][reward]:".print_r($_POST,1));
        
        // 投资成功
        if ($verifySignature) {

            if (in_array($ResultCode, array('88'))) {
                
                $tmp = json_decode($LoanJsonList, 1);
                $tmp = $tmp[0];

                // [success]成功
                $key  = 'Cache:lock:validate:investNotify:'.$tmp['OrderNo'];
                $ikey = "Cache:project:row".$tmp['BatchNo'];

                if (! $this->cache->get($key)) {

                    $this->cache->save($key, 'start', 60);
                    

                    
                    $this->cache->delete($key);
                    $this->cache->delete($ikey);
                    $this->cache->delete('Cache:info:user:'.$Remark1);
                    $this->cache->delete('Cache:info:funds:assets:'.$Remark1);
                    echo "SUCCESS";
                }
            }
        } else {

            $errlog = $dataStr."\n"."[SignInfo:]:".$SignInfo;
            logfile("[qdd][rewardNotify][dataStr:]:".$errlog,'validate_err');
        }
    }

    // 发红包
    private function _sendRedPackage($id,$type,$trigger = 1){
        
        // 红包开关
        if (!$trigger) {

            return FALSE;
        } else {

            // load model
            $this->load->model('red_package_model','mred','default');
            $this->load->model('red_package_user_model','mred_user');
            
            // 获取用户类型
            $info   = $this->maccount->get_one($id);
            if ($info['user_role'] != 0) {
                
                return 1;
            }

            // 获取红包模型
            $where  = array("type"=>$type);
            $result = $this->mred->get_one($where);

            // 构造数据
            $tmp['money']         = $result['money'];
            $tmp['type']          = $type;
            $tmp['require_money'] = $result['require_money'];
            $tmp['require_cycle'] = $result['require_cycle'];
            $tmp['note']          = $result['note'];
            $tmp['create_at']     = date("Y-m-d H:i:s");
            $tmp['expire_at']     = date("Y-m-d H:i:s",strtotime("+".$result['expire_days'].'days'));
            $tmp['aid']           = $id;

            // 创建返回
            if ($redP = $this->mred_user->get_one(array('aid' => $id, 'type' => $type))) {

                return $redP['id'];
            }
            return $this->mred_user->create($tmp);
        }
    }
}
